package com.ccsoft.thread.service;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 2021年12月17日 14:46:38 chanchaw
 * 使用 ReentrantLock 实现交替输出
 */
public class No13SupersedeReentrantLock {
    public static void main(String[] args) {
        SupersedeReentrantLock supersedeReentrantLock = new SupersedeReentrantLock(5);
        Condition a = supersedeReentrantLock.newCondition();
        Condition b = supersedeReentrantLock.newCondition();
        Condition c = supersedeReentrantLock.newCondition();

        new Thread(() -> {
            supersedeReentrantLock.print("a",a,b);
        },"ta").start();

        new Thread(() -> {
            supersedeReentrantLock.print("b",b,c);
        },"tb").start();

        new Thread(() -> {
            supersedeReentrantLock.print("c",c,a);
        },"tc").start();

        supersedeReentrantLock.lock();
        try {
            a.signal();
        }finally {
            supersedeReentrantLock.unlock();
        }

    }
}

class SupersedeReentrantLock extends ReentrantLock {
    int loopNumber;

    public SupersedeReentrantLock(int loopNumber) {
        this.loopNumber = loopNumber;
    }

    public void print(String printContent,Condition currentCondition,Condition nextCondition){
        for (int i = 0; i < loopNumber; i++) {
            lock();

            try {
                currentCondition.await();
                System.out.print(printContent);
                nextCondition.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally{
                unlock();
            }
        }
    }
}
